package com.itheima.ydd.controller;



import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.service.IYddLinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_link")
public class YddLinkController {
    @Autowired
    private IYddLinkService yddLinkService;

    /**
     * 链接列表
     * @param type
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R linkList(String type,String page,String limit){
        //分页构造器
        Page<YddLink> linkPage = new Page<>(Long.parseLong(page),Long.parseLong(limit));
        LambdaQueryWrapper<YddLink> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type!=null,YddLink::getType,type);
        yddLinkService.page(linkPage,lqw);
        R r = R.success("count", linkPage.getTotal());
        r.putData("totalPages",linkPage.getPages());
        r.putData("pageSize",linkPage.getSize());
        r.putData("currentPage",linkPage.getCurrent());
        r.putData("data",linkPage.getRecords());
        return r;
    }

    /**
     * 添加数据
     * @param yddLink
     * @return
     */
    @PostMapping("/add")
    public R linkAdd(@RequestBody YddLink yddLink){
        boolean result = yddLinkService.save(yddLink);
        if (result){
            return R.success("data","添加成功");
        }
        return R.error("添加失败");
    }

    /**
     * 链接详情
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R rowInfo(String id){
        YddLink yddLink = yddLinkService.getById(id);
        if (yddLink==null){
            return R.error("该链接不存在,请刷新页面重试");
        }
        HashMap map = JSON.parseObject(JSON.toJSONString(yddLink), HashMap.class);
        R r = R.success();
        r.setData(map);
        return r;
    }

    /**
     * 修改链接
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public R linkUpdate(@RequestBody YddLink yddLink){
        boolean result = yddLinkService.updateById(yddLink);
        if (result){
            return R.success();
        }
        return R.error("修改失败,请重试");
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @GetMapping("/del")
    public R linkDel(String id){
        //根据id删除数据
        boolean result = yddLinkService.removeById(id);
        if (result){
            return R.success();
        }
        return R.error("删除失败");
    }

}
